<script lang="ts">
	import Dialog, { Title, Content, Actions, InitialFocus } from '@smui/dialog';
	import Autocomplete from '@smui-extra/autocomplete';
	import Button, { Label } from '@smui/button';
	import { createEventDispatcher } from 'svelte';
	import Textfield from '@smui/textfield';
	import Checkbox from '@smui/checkbox';
	import { shallowClone } from '$utils/clone';
	import { alova } from '$utils/request';
	import { createMessage } from '$components/basic/message';
	import Select, { Option } from '@smui/select';
	import { useCountryStore } from '@/store/modules/country';

	const dispatcher = createEventDispatcher();

	let open = false;
	let list: { Label: string; value: number }[] = [];

	export let title = 'Edit Address';
	export async function init(name, item = {} as any) {
		title = name;

		address = (() => {
			const result = shallowClone(item);
			result.private = Boolean(item.private);
			result.isDefault = Boolean(item.isDefault);
			return result;
		})();

		const countryStore = useCountryStore();
		const countries = await countryStore.getCountries();
		list = countries.map(({ name: Label, id: value }) => ({ Label, value }));

		open = true;
	}

	const dataArray = [
		{ require: true, span: 8, type: 'auto', label: 'Country: *', value: 'aCountryName' },
		{ require: true, span: 8, type: 'text', label: 'Postcode: ', value: 'postcode' },
		{ require: true, span: 8, type: 'text', label: 'Province: ', value: 'aProvince' },
		{ require: true, span: 8, type: 'text', label: 'City: ', value: 'aCity' },
		{ require: true, span: 16, type: 'text', label: 'Detail: ', value: 'aDetail' },
		{ require: true, span: 8, type: 'text', label: 'First Name: ', value: 'fName' },
		{ require: true, span: 8, type: 'text', label: 'Last Name: ', value: 'lName' },
		{ require: true, span: 8, type: 'text', label: 'Email: ', value: 'email' },
		{ require: false, span: 8, type: 'text', label: 'Phone: ', value: 'phone' },
		{ require: false, span: 8, type: 'text', label: 'Company Name: ', value: 'companyName' },
		{ require: false, span: 4, type: 'checkbox', label: 'Is Default: ', value: 'isDefault' },
		{ require: false, span: 4, type: 'checkbox', label: 'Private: ', value: 'private' }
	];

	const getDefault = () =>
		dataArray.reduce((acc, item) => {
			return { ...acc, [item.value]: item.type === 'checkbox' ? false : '' };
		}, {});

	export let address = getDefault();

	const on_confirm = async () => {
		for (const item of dataArray) {
			if (item.require && !address[item.value]) {
				createMessage({
					type: 'warning',
					message: `${item.label} is required`,
					duration: 2000
				});
				return;
			}
		}

		await alova.Post('/member-address/edit', address);
		await dispatcher('fresh');
		createMessage({
			type: 'success',
			message: title.charAt(0) === 'A' ? 'Add Success' : 'Edit success',
			duration: 2000
		});
	};
	const on_cancel = () => (address = getDefault());

	const setCountry = ({ detail }: CustomEvent) => {
		address['aCountryId'] = list.find(({ Label }) => Label === detail)?.value;
	};
</script>

<Dialog
	bind:open
	fullscreen={true}
	aria-labelledby="simple-title"
	aria-describedby="simple-content"
	container$class="items-start!"
	surface$class="max-w-100% mt-200px"
	on:SMUIDialog:closed={on_cancel}
>
	<div class="pl-20px">
		<Title id="simple-title">{title}</Title>
	</div>
	<div id="simple-content" class="w-full p-20px!">
		<form class="w-full grid grid-cols-24 gap-8px">
			{#each dataArray as item}
				<div class="flex flex-row items-center" style={'grid-column: span ' + item.span}>
					{#if item.type === 'text'}
						<Textfield
							type="text"
							class="w-full"
							label={item.label}
							required={item.require}
							variant="filled"
							bind:value={address[item.value]}
						/>
					{:else if item.type === 'checkbox'}
						<Label class="indent-sm">{item.label}</Label>
						<Checkbox bind:checked={address[item.value]} />
					{:else if item.type === 'auto'}
						<Autocomplete
							class="w-full"
							on:SMUIAutocomplete:selected={setCountry}
							textfield$variant="filled"
							textfield$style="width: 100%;"
							options={list.map((i) => i.Label)}
							bind:value={address[item.value]}
							menu$class="max-h-200px!"
							label={item.label}
						/>
					{:else if item.type === 'select'}
						<Select
							variant="filled"
							class="w-full"
							required={item.require}
							bind:value={address[item.value]}
							label={item.label}
							menu$class="max-h-200px!"
						>
							{#each list as country}
								<Option value={country.value}>{country.Label}</Option>
							{/each}
						</Select>
					{/if}
				</div>
			{/each}
		</form>
	</div>
	<div class="h-30px w-full"></div>
	<Actions>
		<Button on:click={on_cancel} variant="raised"><Label>cancel</Label></Button>
		<Button on:click={on_confirm} variant="raised" use={[InitialFocus]}>
			<Label>confirm</Label>
		</Button>
	</Actions>
</Dialog>
